package com.znsd.zl.app.wechat.utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.znsd.zl.app.wechat.config.WeChatPayConfig;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 *      微信支付工具类
 * </p>
 *
 * @ClassName WeChatPayUtils
 * @Description TODO
 * @Author jaypddD
 * @Date 2020/8/27 21:52
 * @Version v1.0
 */
@Slf4j
@Component
public class WeChatPayUtils {

	@Resource
	private WeChatPayConfig payConfig;

	/**
	 * 创建商户订单，获取微信预支付预支付订单信息
	 * @param map           商户订单信息
	 * @return              返回预支付订单信息
	 * @throws Exception    xml文件转换失败
	 */
	public Map<String, String> unifiedOrder(Map<String, String> map) throws Exception {
		OkHttpClient client = new OkHttpClient();
		String s = WXPayUtil.mapToXml(map);
		log.info("【小程序支付】签名xml：{}", s.toString());
		RequestBody requestBody = RequestBody.create(
				MediaType.parse("application/json; charset=utf-8"), s);
		Request request = new Request.Builder()
				.url(payConfig.getPayUrl())
				.post(requestBody)
				.addHeader("Content-Type", "application/json")
				.build();
		ResponseBody responseBody = null;
		Map<String, String> resultMap = null;
		try {
			responseBody = client.newCall(request).execute().body();
			resultMap = WXPayUtil.xmlToMap(responseBody.string());
		} catch (IOException e) {
			log.error("【小程序支付】预支付订单信息获取失败，失败原因：{}", resultMap.toString());
		} catch (Exception e) {
			log.error("【微信工具类】xml转换失败，失败原因：{}", map.toString());
		}
		return resultMap;
	}

}
